%% Step 4

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author: JdG,AL,IM by Christopher Evans at UPF 
% 
% Purpose: Computes the main algorithm to work out wages, prices, 
% endogenous labour for the baseline calibration (no shocks)
%
% Output:  converged expenditure hat, wage hat and prices, which are
%          calculated via Equilibrium_CES.m, which calls up the following
%          functions:
%           1) PriceLoop_CES.m
%           2) TradeShare_CES.m
%           3) Expenditure_CES.m
%           4) LabourMarketCondition_CES.m
%
% NEW: For all code, we will change the subscripts to match those in
% master_notes3.pdf and the draft. I.e., we will change to {mn,ij} pairs,
% which represent country pair {mn} and sector pair {ij}. Global variables 
% changed and slight modification to file structure for calling up data.
% We also get rid of gamma_type variable. What previously _2.csv. files
% slightly as well as adjusting in our new directory.
%
% More substantial changes in this file:
%   1) Ignore the sector model not being run and initialize hat variables
%      to a vector of ones to begin with (done in previous code)
%   2) Use updated functions, with CES appended:
%      - EquilibriumCES_fun.m
%      - PriceLoopCES_fun.m
%      - TradeShareCES_fun.m
%      - ExpenditureCES_fun.m
%      - LabourMarketConditionCES_fun.m
%
% We also get rid of using the .(ISO{}) cell call up for the gammas and
% instead use a large matrix saved in Step2. This will help save on loops
% and speed up the proceedure.
%
% Last Updated: 5/02/2019 by IM & JDG
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

global alphaT rhoT lambdaT etaT rho sigma lambda eta varphi ...
    tol maxit Pi_hat_n D_hat_n Xi_hat_mnjf Xi_hat_mnj a_hat_f a_hat ...
    N J FI_J france countrysecD firmsecD_sorted start start_sorted ...
    sum_by_country_dummy ISO ... 
    sL_n sPi_n sD_n alpha_WIOD_j alpha_WIOD_francej labour_share_PWT

%% Algorithm

tol      = 1E-5; %Tolerance allowed until price or wage converged
maxit    = 1E+10; %Maximum iterations to loop over

% No data/assumptions for shocks at the moment just assume nothing changes
% How to get firm profits

% pi_inj: Export shares. Initially set all to 1 as this is the share of 
%          firm f in total exports from country n to country k in sector j'
%          However this is the sector level equivalent to the firm
%          variable. Therefore we set export shares equal to 1 for all
%          tradable sectors. We then set export share equal to 0 for all
%          non-tradable sectors. The important exception here is that
%          non-tradable to non-tradable sector trade within the same
%          country is set equal to 1. 

% Here we are just changing the variable name (this can be cleaned up
% earlier in Step 1 when it was initially defined).

% pi_mnj = pi_nkjp;

%Frisch elasticity for GHH preferencewhatss, placeholder for now 

%varphi = 3;

% Assumptions needed, will change later

% Share of labour in total final consumption (need to make assumption 
% or collect data)

sL_n = ones(1,N)*0.8; 

%share of profits in total final consumption (should have this data)
   
sPi_n = ones(1,N)*0.15; 

%share of trade deficit in total final consumption (should have this data)

sD_n = ones(1,N)*0.05; 

% Intermediate, export, and labor shares. Set to data. Will be updated in
% equilibrium for next period values, which will be used as starting values
% for counterfactuals

pi_M0 = gamma;
pi_l0 = alpha_WIOD_nj';

pi_mnj0 = pi_mnj;
pi_mnjf0 = pi_mnj_sorted;

pi_M_f0 = GAMMA_sorted_matrix;
pi_l_f0 = alpha_f_sorted;

% Also set country shares as initial

pi_c_mnj0 = pi_c_mnj;
pi_c_nj0 = pi_c_nj;

% Set bilateral trade flows as initial

X_mnj0 = X_mnj;

%% Initialise price hat and wage hat guesses:
    
% P_hat: Initialise the Price hat equation 

P_hat_mnj0 = ones(J*N,N);

% Initialisation of wage shock

w_hat0 = ones(1,N);

% Initiliaze wage guess from a previous mode solution ==> DID NOT WORK!
% First run gave imaginary numbers for a solution!!!!

%load MAT/w_hat_init.mat;
%w_hat0 = w_hat_init; 

% Initial guess for the change in expenditures 

X_hat_mnj0= ones(N*J,N);
    
% Initial guess for the change in markups 

mu_hat_mnjf0= ones(FI_J,N);

%% SHOCKS %%

% These shocks are all set to 1 (no shocks) in the baseline calibration
    
%   These shocks here are used to setup the model such that we solve
%   for the new X (expenditure matrix) with labour market condition
%   holding (no wedges).

% Pi_hat: Change in profits per country

Pi_hat_n = ones(1,N);

% D_hat: Change in trade deficit 

D_hat_n = ones(1,N);

% Taste shock - for France only

Xi_hat_mnjf = ones(FI_J,N); 

% Taste shock - for sectors only (countries except France)

Xi_hat_mnj = ones(N*J,N);

% Productivity shock, a is firm specific - France only

a_hat_f = ones(FI_J,1); 

% Productivity shock, a is for sectors - countries except France

a_hat = ones(J*N,1);

% Function to solve the equilibrium 
% Run the algorithm based on constant markups to initiate wage adjustments
[P_hat_n,P_hat_nj,P_hat_mnj,w_hat,X_hat_mnj,pi_mnjf1,pi_mnj1,...
    pi_c_mnj1,pi_c_nj1,pi_M1,pi_l1,pi_M_f1,pi_l_f1,PC_hat_n1,...
    pseudo_final_goods1, pseudo_intermediates1,mu_hat_mnjf]= ...
    EquilibriumCES_fun_approx_Olig(P_hat_mnj0,w_hat0,pi_mnj0,pi_M0,pi_M_f0,...
    pi_l0,pi_l_f0,pi_mnjf0,pi_c_mnj0,X_hat_mnj0,pi_c_nj0,PC_n,zeta_mnj,X_mnj0,mu_hat_mnjf0);